<template>
	<view class="content  zl-p-b-10">
		<view class="box  zl-flex zl-flex-wrap">
			<!-- <view class="item zl-m-b-20" v-for="(item,index) in data_list" :key="index"
				:class="index%4===3?'':'zl-m-r-20'">
				<image v-if="mediaType==='video'" @click="previewVideo(item)" class="item_img"
					:src="item.url+OssVideoShrink" mode="aspectFill"></image>
				<image v-else @click="preview(index,data_list)" :src="item.url" class="item_img" mode="aspectFill">
				</image>
				<image v-if="mediaType==='video'" class="play" @click="previewVideo(item)"
					src="/static/icon/play.png"></image>
				<image class="del" @click="del(index)" src="/static/icon/del.png"></image>
			</view> -->
			<!-- 		<view v-if="data_list.length<len" @click="goChoose()" class="item add zl-m-b-20 zl-flex zl-row-center">
				<image src="/static/icon/add-black.png" mode="aspectFill"></image> 
			</view> -->
			<view @click="goChoose()" class="uploadBtn zl-m-b-20 zl-flex zl-row-center">
				我知道了，去上传训练视频
			</view>
		</view>
		<uni-popup :animation="false" ref="popup" type="center" background-color="#fff"
			border-radius="20rpx 20rpx 20rpx 20rpx">
			<view class=""
				style="width: 560rpx;height: auto;background-color: #fff;border-radius: 20rpx;padding:40rpx 30rpx;">
				<!-- <view class="" style="display: flex;justify-content: flex-end;width: 100%;">
					<image @click="close()" style="width: 34rpx;height: 34rpx;" src="../static/icon/pop_close.png"
						mode=""></image>
				</view> -->
				<view class="pro_title">上传进度</view>
				<view class="pros zl-m-t-20">
					<progress :percent="pro" show-info stroke-width="3" />
				</view>

			</view>
		</uni-popup>
		<uni-popup background-color="#fff" ref="pop2" type="bottom" border-radius="20rpx 20rpx 0 0">
			<view class="pop-box">
				<view class="pop-top zl-flex zl-row-between">
					<view class="video_poo_title">预览素材</view>
					<image @click="closeVideo()" style="width: 30rpx;" src="/static/icon/pop_close.png" mode="widthFix">
					</image>
				</view>
				<view class="popup-video">
					<video v-if="isVideo" :src="activeVideo.url" :controls="true"
						:poster="activeVideo.url+ossVideoCover"></video>
				</view>
			</view>
		</uni-popup>
		<uni-popup :animation="false" ref="Cropping" type="center" background-color="#fff"
			border-radius="20rpx 20rpx 20rpx 20rpx" :is-mask-click="false">

			<view class="tip-box zl-flex-col zl-col-center zl-text-center">
				<!-- <image style="width: 120rpx;" src="/static/icon/fail.png" mode="widthFix"></image> -->
				<view class="zl-color-000 zl-font-40 zl-font-600 zl-m-t-36">是否前往裁剪视频</view>
				<view class="zl-color-666 zl-font-24 zl-m-t-40"> 裁剪视频可能会导致
					<text style="color: #EB5E00;">清晰度下降，</text>
					</br>请确认是否前往视频裁剪！
				</view>
				<view @click="goCropp()" class="btn zl-m-t-66 zl-theme-btn">前往裁剪 </view>
				<view class="btn zl-m-t-32 zl-cancel-btn" @click="cancelCropp()"> 直接上传 </view>
			</view>

			<image @click="$refs.Cropping.close()"
				style="width: 80rpx;height:80rpx;margin-top: 70rpx;margin-left: 260rpx;z-index: 999;"
				src="/static/icon/close-w.png"></image>


		</uni-popup>
	</view>
</template>
<script>
	export default {
		name: "media_group",
		props: {

			mediaType: {
				type: String,
				default: 'video'
			},
			// 最小时长
			min: {
				type: Number,
				default: 10
			},
			// 最大时长
			max: {
				type: Number,
				default: 60
			},
			// 最多数量
			len: {
				type: Number,
				default: 1
			},
			// 素材列表
			list: {
				type: Array,
				default: []
			},
			isWidth: {
				type: Boolean,
				default: false
			},
			type: {
				type: Number,
				default: 0
			},
			size: {
				type: Number,
				default: 500
			}
		},
		data() {
			return {
				data_list: [],
				// 上传进度条
				pro: 0,
				pro_count: 0,
				// 封面图配置
				OssVideoShrink: getApp().globalData.OssVideoShrink,
				ossVideoCover: getApp().globalData.ossVideoCover,
				// 预览视频
				show: false,
				isVideo: false,
				activeVideo: {},
				tempFiles: []
			};
		},
		mounted() {
			if (this.list && this.list.length > 0) {
				this.data_list = [].concat(this.list);
			}

		},
		watch: {
			list(newVal, oldVal) {
				this.data_list = newVal;
			}
		},
		methods: {

			close() {
				this.$refs.popup.close()

			},


			goUp() {
				this.choose()
			},
			goChoose() {
				this.choose()
			},
			cancelCropp() {
				this.$refs.Cropping.close();
				this.uploadAll(this.tempFiles, false)
			},
			goCropp() {
				if (uni.openVideoEditor) {
					uni.openVideoEditor({
						filePath: this.tempFiles[0].tempFilePath,
						minDuration: this.min.toString(),
						maxDuration: this.max.toString(),
						success: result => {
							result.duration = Math.floor(result.duration * 0.001)
							this.uploadAll([result], true)
							// console.log(result, '剪辑后');
						},
						fail: err => {
							console.log(err);
							// this.uploadAll(this.tempFiles, false)
						}
					})
				} else {
					this.uploadAll(this.tempFiles, false)
				}
			},
			// 选择素材
			choose() {
				console.log(this.max);
				var count = 9;
				if ((this.len - this.data_list.length) < 9) {
					count = this.len - this.data_list.length
				}
				// #ifdef MP-WEIXIN	
				if (this.mediaType == "video") {
					uni.chooseMedia({
						count: count,
						mediaType: [this.mediaType],
						sourceType: ['album'],
						// maxDuration: this.max,
						sizeType: ['original', 'compressed'],
						compressed: false,
						success: res => {
							// console.log(res, '选择返回的数据');
							if (res.tempFiles.length == 1 && this.mediaType == "video") {
								this.tempFiles = res.tempFiles;
								this.$refs.Cropping.open()
								return
								// console.log(res.tempFiles[0]);
								// if (uni.openVideoEditor) {
								// 	uni.openVideoEditor({
								// 		filePath: res.tempFiles[0].tempFilePath,
								// 		minDuration: this.min.toString(),
								// 		maxDuration: this.max.toString(),
								// 		success: result => {
								// 			result.duration = Math.floor(result.duration * 0.001)
								// 			this.uploadAll([result], true)
								// 			// console.log(result, '剪辑后');
								// 		},
								// 		fail: err => {
								// 			this.uploadAll(res.tempFiles, false)
								// 		}
								// 	})
								// } else {
								// 	this.uploadAll(res.tempFiles, false)
								// }
							} else {
								this.uploadAll(res.tempFiles, false)
							}
						},
						fail: err => {
							console.log(err);
							if (err.errMsg === "chooseMedia:fail cancel") {
								console.log('用户取消操作,不需要弹框');
							} else {
								uni.showModal({
									title: '选择文件异常',
									content: err.errMsg,
								})
							}
							// this.$util.msg(err.errMsg)
						},
					});
				} else {
					uni.chooseImage({
						count: count,
						sourceType: ['album', 'camera'],
						sizeType: ['original'],
						success: res => {
							// console.log(res);
							this.uploadAll(res.tempFiles, false);
						}
					})
				}
				// #endif
				// #ifndef MP-WEIXIN
				// this.$util.msg('当前平台暂不支持上传！');
				if (this.mediaType === 'video') {
					uni.chooseVideo({
						sourceType: ['album', 'camera'],
						compressed: false,
						maxDuration: this.max,
						success: res => {
							// console.log(res.tempFilePath);
							this.uploadAll([res], false);
						}
					})
				} else {
					uni.chooseImage({
						count: count,
						sourceType: ['album', 'camera'],
						sizeType: ['original'],
						success: res => {
							// console.log(res);
							this.uploadAll(res.tempFiles, false);
						}
					})
				}
				// #endif
			},
			// h5/app媒体文件选择
			handleChooseVideo() {
				let extension = this.mediaType === 'image' ? ['.png', '.jpg', '.jpeg'] : ['.mp4', '.mov']
				var count = 9;
				if ((this.len - this.data_list.length) < 9) {
					count = this.len - this.data_list.length
				}
				uni.chooseFile({
					count: count, //默认100
					extension: extension,
					type: this.mediaType,
					success: async (res) => {
						console.log(res);
						if (this.mediaType === 'video') {
							let file = res.tempFiles
							for (const item of file) {
								const duration = await this.getVideoDurationFromBlob(item.path);
								item.duration = duration;
							}
							this.uploadAll(file, false, true);
						} else {
							this.uploadAll(res.tempFiles, false, true);
						}
					},
				});
			},
			async getVideoDurationFromBlob(blobObject) {
				return new Promise((resolve) => {
					const videoElement = document.createElement('video');
					videoElement.src = blobObject;
					videoElement.addEventListener('loadedmetadata', () => {
						const duration = videoElement.duration;
						resolve(duration);
					});
				});
			},
			async uploadAll(list, flag, ish5up) {
				this.$refs.Cropping.close();

				console.log(list);
				let item = list[0]
				var suffix = item.tempFilePath.substr(item.tempFilePath.lastIndexOf("."));
				var fileName = new Date().getTime() + '_' + this.$util.randomString(8) + suffix;

				// 获取上传签名
				var signRes = undefined;
				try {
					signRes = await this.api.clone.applyuploaddigital({
						fileName: fileName,
					});
					if (signRes.code != 0) {
						this.$util.msg(signRes.msg);
						return;
					}
				} catch (e) {
					//TODO handle the exception
					// #ifdef MP-WEIXIN
					wx.reportEvent("media_upload", {
						exception: JSON.stringify(e)
					})
					// #endif
					this.$util.msg('上传初始化失败！');
					return;
				}
				if (!signRes || !signRes.data) {
					// #ifdef MP-WEIXIN
					wx.reportEvent("media_upload", {
						api_exception: '获取签名失败！'
					})
					// #endif
					this.$util.msg('上传初始化失败！');
					return;
				}
				var sign = signRes.data;
				// console.log(sign,'签名');
				this.pro_count = list.length;
				this.pro = 0;
				this.$refs.popup.open()
				if (this.mediaType === 'image') {
					item.tempFilePath = item.path
				}
				if (this.mediaType === 'video') {
					console.log(item);
					let ext = ''
					if (ish5up) {
						let imgIndex = item.type.lastIndexOf("/");
						ext = item.type.substr(imgIndex + 1).toLowerCase();
					} else {
						let imgIndex = item.tempFilePath.lastIndexOf(".");
						ext = item.tempFilePath.substr(imgIndex + 1).toLowerCase();
					}
					if (ext !== "mov" && ext !== "mp4") {
						this.$util.msg('素材格式不支持！');
						this.$refs.popup.close()
						return
					}
					if (item.size > 1024 * 1024 * this.size) {
						this.$refs.popup.close()
						return this.$util.msg(`文件超出大小，请上传低于${this.size}兆的文件`)
					}
					if (item.duration < this.min || item.duration > this.max) {
						this.$util.msg('素材时长不满足要求！');
						this.$refs.popup.close()
						return
					}
				} else if (this.mediaType === 'image') {
					// console.log(item);
					let imgIndex = item.tempFilePath.lastIndexOf(".");
					let ext = item.tempFilePath.substr(imgIndex + 1).toLowerCase();
					if (ext !== "png" && ext !== "jpg" && ext !== "jpeg") {
						this.$util.msg('素材格式不支持！');
						this.$refs.popup.close()
						return
					}
				}
				// continue;
				try {
					var uploadRes = await this.upload(sign, item.tempFilePath);
					// console.log(uploadRes.url);
					if (this.mediaType === 'video') {
						// this.data_list.push({
						// 	url: uploadRes,

						// });
						this.data_list = [].concat(uploadRes)
					}
					console.log(this.data_list);
				} catch (e) {
					this.$util.msg(e.message || '上传失败！');
					this.pro = 0;
				}

				this.$refs.popup.close()
				setTimeout(() => {
					this.pro_count = 0;
					this.pro = 0;
				}, 1000);
				this.success();
			},
			async upload(sign, tempFilePath) {


				// delete sign.formData.Folder;
				// sign.formData.Key = fileName;
				// console.log(sign);
				return await new Promise((resolve, reject) => {
					var task = uni.uploadFile({
						url: sign.host,
						filePath: tempFilePath,
						fileType: 'video',
						name: 'file',
						formData: sign.formData,
						timeout: 3600000,
						success: (res) => {
							if (res.statusCode === 200) {
								try {
									let data = JSON.parse(res.data);

									if (data.code === 0) {
										resolve(data.data);
									} else {
										reject(new Error(data.msg))
									}
								} catch (e) {
									reject(new Error('解析上传结果失败！'))
								}
							} else {
								reject(new Error('上传失败！'));
							}
						},
						fail: (err) => {
							// #ifdef MP-WEIXIN
							wx.reportEvent("media_upload", {
								aliyun_exception: JSON.stringify(err),
							})
							// #endif
							reject(new Error('上传失败！'));
						}
					});
					task.onProgressUpdate((pro) => {
						this.pro = pro.progress;
						// console.log(this.pro);
					});
				});
			},
			success() {
				this.$emit('success', this.data_list);
			},
			del(index) {
				this.data_list.splice(index, 1);
				this.success();
			},
			previewVideo(video) {
				this.isVideo = true;
				this.activeVideo = video;
				this.$refs.pop2.open()
			},
			closeVideo() {
				setTimeout(() => {
					this.activeVideo = {};
					this.isVideo = false;
				}, 250);
				this.$refs.pop2.close()
			},
			preview(index, list) {
				var urls = list.map((item, i) => {
					return item.url;
				})
				uni.previewImage({
					current: index,
					urls: urls
				});
			}
		}
	}
</script>
<style scoped lang="scss">
	.popup_bg {
		width: 100%;
		height: 100vh;
		background-color: rgba(0, 0, 0, 0.6);
		position: fixed;
		top: 0;
		left: 0;
		z-index: 99999;

		.bottom-box {
			position: absolute;
			left: 40rpx;
			bottom: 32rpx;

			.choose-k {
				width: 30rpx;
				height: 30rpx;
				background: #FFFFFF;
				border-radius: 4rpx;
			}
		}

		.closebtn {
			width: 72rpx;
			height: 72rpx;
		}

		.popup_bg_content {
			position: relative;
			width: 100%;
			height: 100%;

			.popup_box {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				width: 600rpx;

				.popup_cnt {
					width: 100%;
					border-radius: 20rpx;
					background-color: #FFFFFF;
					padding: 78rpx 40rpx 50rpx;

					.popup_btn {
						width: 350rpx;
						height: 88rpx;
						border-radius: 44rpx;
					}

					.popup_btn_disable {
						background-color: #FFFFFF;
						color: #999999;
						border: 1px solid #CCCCCC;
					}
				}

				.save_des {
					width: 380rpx;
					padding: 16rpx 20rpx;
					position: relative;
					background-color: #FFFFFF;
					box-shadow: 0 2rpx 12rpx 0 rgba(0, 0, 0, 0.12);
					border-radius: 20rpx;

					image {
						width: 40rpx;
						height: 20rpx;
						position: absolute;
						top: -20rpx;
						left: calc(50% - 20rpx);
					}
				}

				.popup_close {
					width: 72rpx;
					height: 72rpx;
					margin: 50rpx auto 0;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}
		}
	}

	.content {
		width: 100%;
		padding-top: 30rpx;

		.box {
			width: 100%;

			.item {
				width: 142rpx;
				height: 142rpx;
				position: relative;

				.item_img {
					width: 100%;
					height: 100%;
					border-radius: 10rpx;
					overflow: hidden;
				}

				.del {
					width: 40rpx;
					height: 40rpx;
					position: absolute;
					top: -20rpx;
					right: -20rpx;
					z-index: 1;
				}

				.play {
					width: 30rpx;
					height: 30rpx;
					position: absolute;
					top: calc(50% - 15rpx);
					right: calc(50% - 15rpx);
					z-index: 1;
				}
			}

			.add {
				background: #F5F5F5;
				border: 1px solid #E4E4E4;
				border-radius: 10rpx;
				overflow: hidden;

				image {
					width: 36rpx;
					height: 36rpx;
				}
			}
		}
	}

	.pro_title {
		font-size: 32rpx;
		font-weight: bold;
		text-align: center;
	}

	.pro_des {
		font-size: 28rpx;
		font-weight: bold;
		text-align: center;
		color: darkblue;
	}

	.video_poo_title {
		width: 100%;
		text-align: center;
		font-size: 30rpx;
		font-weight: 500;
	}

	.popup-video {}

	.popup-video video {
		width: 100%;
		height: 80vh;
	}

	.pop-box {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;

		.pop-top {
			height: 120rpx;
			padding: 0 30rpx;
			border-bottom: 1px solid #ddd;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 36rpx;
			color: #131415;
		}
	}

	.tip-box {
		width: 600rpx;
		background: #FFFFFF;
		border-radius: 18rpx;
		padding: 60rpx 60rpx 48rpx;
        margin-top: -400rpx;

		// position: absolute;
		// top: 50%;
		// left: 50%;
		// transform: translate(-50%, -60%);

		.btn {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 400rpx;
			height: 88rpx;
			border-radius: 44rpx;
		}

		.cancelbtn {
			background: #EEEEEE;
			font-weight: 600;
			font-size: 28rpx;
			color: #000;
		}
	}

	.uploadBtn {
		width: 690rpx;
		height: 110rpx;
		background: #000000;
		border-radius: 18rpx;
		color: #FFFFFF;
		font-size: 32rpx;
	}
</style>